﻿using System;
using VideoServices.Business.Facade;
using VideoServices.Domain.Entities;
using VideoServices.Services.Dto;
using VideoServices.Services.Interface;
using VideoServices.Services.Response;
using VideoServices.Services.Response.Extension;
using VideoServices.Services.Translation;
using VideoServices.Services.Translation.Base;
using VideoServices.Services.Translation.Factory;

namespace VideoServices.Services
{
    public class StockService : IStockService
    {
        #region Implementation of IStockService

        /// <summary>
        /// Gets the item by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public Response<StockDto> GetItemById(int id)
        {
            var response = new Response<StockDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoServicesFacade.Instance;
                Stock stock = facade.GetItemById(id);
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(StockTranslator));
                response.ResponseObject = translator.TranslateToDto<Stock, StockDto>(stock);
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.Add(new Error("Fatal error occured.", ex.Message));
            }
            return response;
        }

        /// <summary>
        /// Creates the item.
        /// </summary>
        /// <param name="newStock">The new stock.</param>
        /// <returns></returns>
        public Response<StockDto> CreateItem(StockDto newStock)
        {
            var response = new Response<StockDto>();
            response.IsSuccessful = true;
            try
            {
                var facade = VideoServicesFacade.Instance;
                ITranslator translator = TranslatorFactory.GetTranslatorByType(typeof(StockTranslator));
                Stock stockEntity = translator.TranslateToEntity<StockDto, Stock>(newStock);
                Stock savedStock = facade.CreateItem(stockEntity);
                response.ResponseObject = translator.TranslateToDto<Stock, StockDto>(savedStock);
                response.Messages.AddSuccessfulSaveMessage("Stock Item");
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.Add(new Error("Fatal error occured.", ex.Message));
            }
            return response;
        }

        #endregion
    }
}
